<?php 
class Node_model_node_image extends Model {
    private $table = 'node_image';
    
    public function add($node_id, $key, $src = '', $alt = '') {
        $node_id = (int) $node_id;
        if ($node_id <= 0) {
            return false;
        }
        $src = trim($src);
        
        
        $key = trim($key);
        $alt = trim($alt);
        
        $id = $this->_exists($node_id, $key);
        
        if ($id > 0) {
            if ( ! empty($src)) {
                $data['src'] = $src;
            }
            if ( ! empty($alt)) {
                $data['alt'] = $alt;
            }
            if ($data) {
                return $this->db->update($this->table, $data, array('id' => $id));
            }
            
        } else {
            if (empty($src)) {
                return false;
            }
            return $this->db->insert($this->table, array(
                'node_id'   => $node_id,
                'key'       => $key,
                'src'       => $src,
                'alt'       => $alt
            ));
        }
        
        return false;
        
    }
    
    public function entry($node_id, $key) {
        $node_id = (int) $node_id;
        
        if ($node_id <= 0) {
            return false;
        }
        
        $key = trim($key);
        if (empty($key)) {
            return false;
        }
        
        $key = $this->db->escape_str($key);
        
        $sql = "SELECT `src`, `alt` FROM `{$this->table}` WHERE `node_id`='{$node_id}' AND `key`='{$key}' LIMIT 1";
        
        return $this->db->row($sql);
    }
    
    private function _exists($node_id, $key) {
        $sql = "SELECT `id` FROM `{$this->table}` WHERE `node_id`='{$node_id}' AND `key`='{$key}' LIMIT 1";
        if ($row = $this->db->row($sql)) {
            return $row['id'];
        } else {
            return 0;
        }
    }
}
?>